/*
 * console.c
 *
 * Copyright (C) 2011 - Dr.NP
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @version console.c 1.0.0
 * @package console
 * @author Dr.NP <np@bsgroup.org>
 * @update 03/18/2011
 */

/**
 * Client console
 *
 * === CHANGELOG ===
 * [03/18/2011] - Creation
 */

#include "bsp.h"

#include "libs/core/bsp_core.h"
#include "libs/core/bsp_socket.h"
#include "libs/core/bsp_utils.h"

#include "libs/status/bsp_status.h"
#include "libs/app/bsp_app.h"
#include "libs/app/bsp_script.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/epoll.h>

#define DEFAULT_ADDR                            "127.0.0.1"
#define DEFAULT_PORT                            65100

int console_on_data(int, char *, size_t);
void console_on_close(int);
void * msg_loop(void *);

int main(int argc, char **argv)
{
    int res = core_init_minimal(NULL);
    int cnt_id;
    char buff[1024] = {0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x4, 
                        0x1, 0x1, 0x1, 0x2};
    char buff2[1024];
    char c_addr[64] = DEFAULT_ADDR;
    u_int16_t c_port = DEFAULT_PORT;
    
    struct connector_t *c;
    
    if (res == RTN_SUCCESS)
    {
        if (argc > 1)
        {
            strncpy(c_addr, argv[1], 63);
            c_addr[63] = 0x0;
        }

        if (argc > 2)
        {
            c_port = (u_int16_t) atoi(argv[2]);
        }

        fprintf(stderr, "Connect to %s:%d...\n", c_addr, c_port);
        cnt_id = new_connector(TRANSPORT_TCP | EPOLL_MODE_ET, c_addr, c_port);
        
        c = get_connector(cnt_id);
        if (c)
        {
            c->on_data = console_on_data;
            c->on_close = console_on_close;

            core_add_connector(cnt_id);

            while (1)
            {
                fprintf(stderr, "Enter to send input data from input.dat\n");
                
                fgets(buff2, 1023, stdin);
                append_connector(cnt_id, (const char *) buff, 12);
            }
        }
    }
    
    return RTN_SUCCESS;
}

int console_on_data(int cnt_id, char *data, size_t len)
{
    fprintf(stderr, "Data recieved %d bytes\n", (int) len);
    debug_hex_data(data, len);
    
    return len;
}

void console_on_close(int cnt_id)
{
    fprintf(stderr, "%d disconnected\n", cnt_id);
    
    return;
}

void * msg_loop(void *arg)
{
    return NULL;
}
